package cn.net.lwj.sjqy.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

@Configuration
@MapperScan(basePackages = "cn.net.lwj.sjqy.dao.mysql1",sqlSessionFactoryRef = "mysql1SqlSessionFactory")
public class Mysql1DataSourceConfig {
 
    @Bean(name = "mysql1DataSource") //注入到这个容器
    @ConfigurationProperties("spring.datasource.mysql1") //表示取application.properties配置文件中的前缀
    public DataSource Mysql1DataSource(){
        return DataSourceBuilder.create().build();
    }

    //@Qualifier("xxx")的含义是告诉他使用哪个DataSource
    @Bean(name = "mysql1SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysql1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:mapper/mysql1/*.xml"));
        return sessionFactoryBean.getObject();
    }
    @Bean(name = "mysql1TransactionManager")//配置事务
    public DataSourceTransactionManager Mysql1TransactionManager(){
        return new DataSourceTransactionManager(Mysql1DataSource());
    }

}